#include <bits/stdc++.h>
#ifndef DEBUG
#define debug
#endif
using namespace std;
using i64 = int64_t;

template <template<typename> typename Cmp = greater, typename T>
vector<int> get_next_prev(vector<T> &arr, bool prev = false) {
  int n = arr.size();
  vector<int> res(n);
  stack<int> st;
  for (int i = prev ? 0 : n - 1; prev ? i < n : i >= 0; prev ? ++i : --i) {
    while (!st.empty() && !Cmp<T>()(arr[st.top()], arr[i])) st.pop();
    res[i] = st.empty() ? (prev ? -1 : n) : st.top();
    st.push(i);
  }
  return res;
}
int main() {
  cin.tie(0)->sync_with_stdio(0);
  int n;
  cin >> n;
  vector<int> h(n);
  for (auto &x : h) cin >> x;
  auto prev_g = get_next_prev(h, true);
  long long  ans = 0;
  for (int i = 1; i < h.size(); i++) {
    int limit = prev_g[i];
    for (int lowi = i - 1; prev_g[lowi] >= limit; lowi = prev_g[lowi]) {
      int secondLowi = prev_g[lowi];
      if (secondLowi == -1) break;
      int minh = min(h[i], h[secondLowi]);
      ans += (i - secondLowi - 1) * (minh - h[lowi]);
    }
  }
  cout << ans << endl;
}